package com.bluesky.jwf.config;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ComponentRegistry {
	private static Logger logger = Logger.getLogger(ComponentRegistry.class);

	public static String INCLUDES = ".includes";
	public static String DEFAULT_TEMPLATE = ".defaultTemplate";

	private List<ComponentRegistry> children;
	private String defaultTemplate;

	private Map<String, ComponentInfo> components;

	private String fileName;

	public ComponentRegistry() {
		children = new ArrayList<ComponentRegistry>();
		components = new HashMap<String, ComponentInfo>();
	}

	public void load(String fileName) {
		this.fileName = fileName;
		InputStream is;

		is = getClass().getResourceAsStream(fileName);

		if (is == null)
			throw new RuntimeException("file not found:" + fileName);

		load(is);

	}

	public void load(InputStream is) {

		Properties props = new Properties();

		try {
			props.load(is);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		defaultTemplate = props.getProperty(DEFAULT_TEMPLATE);

		for (String key : props.stringPropertyNames()) {
			String val = props.getProperty(key).trim();
			if (!key.startsWith(".")) {
				ComponentInfo info = new ComponentInfo();
				info.load(val, defaultTemplate);
				components.put(key, info);
			}
		}
		String includes = props.getProperty(INCLUDES);
		if (includes != null) {
			String[] fileNames = includes.split(",");
			for (String s : fileNames) {
				ComponentRegistry reg = new ComponentRegistry();
				reg.load(s);
				children.add(reg);
			}
		}

	}

	public ComponentInfo getComponentInfo(String alias) {
		if (components.containsKey(alias)) {
			logger.debug("find component " + alias + " at " + fileName);
			return components.get(alias);
		}

		for (ComponentRegistry reg : children) {
			ComponentInfo ci = reg.getComponentInfo(alias);
			if (ci != null)
				return ci;

		}
		return null;
	}

}
